import { useState } from "react";
import { Button, Progress, message, Divider, Card } from "antd";
import { PlayCircleOutlined, LoadingOutlined } from "@ant-design/icons";
import Tesseract from "tesseract.js";
import {
  analyzeTextLayoutFromBlocks,
  extractQuestionsFromBlocks,
  analyzeTextLayout,
  extractQuestions,
} from "../utils/textAnalysis";
import { createImageCrops } from "../utils/imageCropper";

const OCRProcessor = ({ image, onOCRComplete, onProcessComplete }) => {
  const [processing, setProcessing] = useState(false);
  const [progress, setProgress] = useState(0);
  const [ocrResults, setOcrResults] = useState(null);
  const [currentStep, setCurrentStep] = useState("");

  const processImage = async () => {
    if (!image) {
      message.error("请先上传图片");
      return;
    }

    setProcessing(true);
    setProgress(0);
    setCurrentStep("初始化OCR引擎...");

    try {
      // 步骤1: OCR识别
      setCurrentStep("正在初始化OCR引擎...");

      // 使用本地worker文件避免CDN加载问题
      const worker = await Tesseract.createWorker("chi_sim+eng", 1, {
        workerPath: "/tesseract/worker.min.js",
        corePath: "/tesseract/tesseract-core-simd.wasm.js",
        langPath: "https://tessdata.projectnaptha.com/4.0.0_best/",
        logger: (m) => {
          if (m.status === "recognizing text") {
            const progress = Math.round(m.progress * 20) + 15; // 15-35%
            setProgress(progress);
            setCurrentStep(`识别进度: ${Math.round(m.progress * 100)}%`);
          }
        },
      });

      setProgress(15);
      setCurrentStep("开始文字识别...");

      const { data } = await worker.recognize(image.url, {}, { blocks: true });
      await worker.terminate();
      console.log("识别文字结果：", data);
      // console.log("识别文字结果：", JSON.stringify(data));
      // 步骤2: 分析文字布局 - 使用新的基于blocks的分析方法
      const layoutAnalysis = analyzeTextLayoutFromBlocks(data);
      setProgress(50);
      setCurrentStep("识别题目结构...");
      console.log("分析文字布局结果：", layoutAnalysis);

      // 步骤3: 提取题目 - 使用新的题目提取方法
      const questions = extractQuestionsFromBlocks(layoutAnalysis, data);
      setProgress(70);
      setCurrentStep("生成图片切割...");
      console.log("提取题目结果：", questions);
      console.log("提取题目结果（详细）：", JSON.stringify(questions, null, 2));
      // 步骤4: 生成切割图片
      const croppedImages = await createImageCrops(image.url, questions);
      setProgress(100);
      setCurrentStep("处理完成!");
      console.log("生成切割图片结果：", croppedImages);
      // 设置结果
      const results = {
        originalData: data,
        layoutAnalysis,
        questions,
        croppedImages,
      };

      setOcrResults(results);
      onOCRComplete(results);
      onProcessComplete(croppedImages);

      message.success(`成功识别并切割 ${questions.length} 道题目!`);
    } catch (error) {
      console.error("OCR处理失败:", error);
      message.error("图片处理失败，请重试");
    } finally {
      setProcessing(false);
      setProgress(0);
      setCurrentStep("");
    }
  };

  return (
    <div>
      <Divider>OCR 识别与处理</Divider>

      <Button
        type="primary"
        size="large"
        icon={processing ? <LoadingOutlined /> : <PlayCircleOutlined />}
        onClick={processImage}
        disabled={processing || !image}
        block
        style={{ marginBottom: 16 }}
      >
        {processing ? "处理中..." : "开始识别和切割"}
      </Button>

      {processing && (
        <div className="ocr-progress">
          <Progress
            percent={progress}
            status="active"
            format={(percent) => `${percent}%`}
          />
          <div
            style={{
              textAlign: "center",
              marginTop: 8,
              fontSize: 12,
              color: "#666",
            }}
          >
            {currentStep}
          </div>
        </div>
      )}

      {ocrResults && (
        <Card size="small" style={{ marginTop: 16 }}>
          <div style={{ fontSize: 12, color: "#666" }}>识别结果统计:</div>
          <div style={{ marginTop: 8 }}>
            <div>
              • 识别文字: {ocrResults.originalData?.words?.length || 0} 个词
            </div>
            <div>• 检测题目: {ocrResults.questions?.length || 0} 道</div>
            <div>
              • 置信度: {Math.round(ocrResults.originalData?.confidence || 0)}%
            </div>
          </div>
        </Card>
      )}
    </div>
  );
};

export default OCRProcessor;
